﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using MyEngineExercise.我的扩展.其他;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Controls;

namespace MyEngineExercise.我的扩展.窗体
{
    public partial class RedLayerAttributeTableForm : Form
    {
        /// <summary>
        /// toc右键菜单所选择的FeatureClass
        /// </summary>
        private IFeatureClass _featureClass = null;


        //private String _oidFieldName = String.Empty;

        /// <summary>
        /// field类型转换后的DataTable
        /// </summary>
        private DataTable _dataTable = null;


        /// <summary>
        /// 保存所有field类型=>DataTable类型的转换信息
        /// </summary>
        private List<FieldToDataTableInfo> _fieldToDataTableInfos = null;


        /// <summary>
        /// oid字段的转换信息
        /// </summary>
        private FieldToDataTableInfo _oidField_FieldToDataTableInfo = null;


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="featureClass"></param>
        public RedLayerAttributeTableForm(IFeatureClass featureClass)
        {
            InitializeComponent();

            _featureClass = featureClass;

            //if (_featureClass.HasOID)
            //    _oidFieldName = featureClass.OIDFieldName;

            this.Text = String.Format("\"{0}\"图层的属性数据", ((IDataset)_featureClass).Name);

            //设置dataGridView1
            dataGridView1.DataSource = bindingSource1;//绑定数据
            dataGridView1.AllowUserToDeleteRows = false;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AllowUserToResizeRows = false;

        }



        /// <summary>
        /// 闪烁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void flashToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CheckSelectRow() == false)
                return;

            IPolygon polygon = _featureClass.UnionPolygons(GetSelectRowsWhereClause());

            if (null == polygon)
                return;

            MapAndPageSync.Instance.DoHookAction(polygon, esriHookActions.esriHookActionsFlash);
        }



        /// <summary>
        /// 定位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void locateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CheckSelectRow() == false)
                return;

            IPolygon polygon = _featureClass.UnionPolygons(GetSelectRowsWhereClause());

            if (null == polygon)
                return;

            MapAndPageSync.Instance.DoHookAction(polygon, esriHookActions.esriHookActionsZoom);
        }


        /// <summary>
        /// 检查所选的行数，不能大于50行
        /// </summary>
        private Boolean CheckSelectRow()
        {
            int selectCount = dataGridView1.SelectedRows.Count;
            if (selectCount > 50)
                MessageBox.Show("你现在选择的行已超过50行，无法执行相关操作！", "选择的行过多", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            return selectCount <= 50;
        }


        /// <summary>
        /// 窗口活动时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RedLayerAttributeTable_Activated(object sender, EventArgs e)
        {
            //移除事件处理程序，即执行一次
            this.Activated -= new EventHandler(RedLayerAttributeTable_Activated);

            toolStripStatusLabel1.Text = "正在打开数据";
            MyAeMethods.Instance.SetBusyState();
            Application.DoEvents();

            #region 转换，并绑定数据
            //将field转换为DataTable
            _dataTable = _featureClass.FieldToDataTable(out _fieldToDataTableInfos);

            //如果不为空
            if (null != _dataTable)
            {
                _oidField_FieldToDataTableInfo = _fieldToDataTableInfos.FirstOrDefault(v => v.FieldType == esriFieldType.esriFieldTypeOID);

                bindingSource1.DataSource = _dataTable;//绑定数据
                bindingSource1.AllowNew = false;//不允许新增

                //设置面积列的格式
                foreach (var areaColumn in _fieldToDataTableInfos.Where(v => v.FieldIndex == -1))
                {
                    //如果该字段的Type是Double
                    if (_dataTable.Columns[areaColumn.DataTableIndex].DataType == typeof(Double))
                    {
                        //从dataGridView1上获取该列
                        var areaCol = dataGridView1.Columns[areaColumn.DataTableIndex];
                        areaCol.DefaultCellStyle.Format = "F02";//设置格式，浮点数，保留2位小数
                    }
                }
            }
            #endregion

            toolStripStatusLabel1.Text = "完成";
            MyAeMethods.Instance.SetDefaultState();
        }


        /// <summary>
        /// 在dataGridView1行头点击鼠标右键，弹出菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            List<Int32> selectedIndexs = new List<Int32>();

            for (int i = 0; i < this.dataGridView1.SelectedRows.Count; i++)
                selectedIndexs.Add(this.dataGridView1.SelectedRows[i].Index);

            if (e.Button == MouseButtons.Right && selectedIndexs.Contains(e.RowIndex))//鼠标右键点击
                contextMenuStrip1.Show(dataGridView1, dataGridView1.PointToClient(Control.MousePosition));
        }


        /// <summary>
        /// 右键菜单弹出前,检查是否允许弹出右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            Boolean enable = null != _oidField_FieldToDataTableInfo
                && dataGridView1.SelectedRows.Count > 0
                && _featureClass.IsPolygon();

            //设置是否可用
            foreach (ToolStripItem item in contextMenuStrip1.Items)
                item.Enabled = enable;
        }


        /// <summary>
        /// 获取当前dataGridView所选的记录对应的过滤语句
        /// </summary>
        /// <returns></returns>
        private String GetSelectRowsWhereClause()
        {
            int oidColumnIndex = _oidField_FieldToDataTableInfo.DataTableIndex;

            StringBuilder whereClauseSb = new StringBuilder("\"" + _featureClass.OIDFieldName + "\" IN(");

            //遍历所选的每一行
            foreach (DataGridViewRow dataGridViewRow in dataGridView1.SelectedRows)
            {
                whereClauseSb.Append(dataGridViewRow.Cells[oidColumnIndex].Value);
                whereClauseSb.Append(",");
            }

            whereClauseSb.Append("-1)");//为什么要添加“-1”，因为如果不加，whereClauseSb结尾会有一个逗号，会导致查询失败

            return whereClauseSb.ToString();
        }
    }
}
